<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">

<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<meta name="theme-color" content="#fff">
<meta name="generator" content="Hexo 5.4.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#fff">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic%7CRoboto+Slab:300,300italic,400,400italic,700,700italic%7CDejaVu+Sans+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css" integrity="sha256-2H3fkXt6FEmrReK448mDVGKb3WW2ZZw35gI7vqHOE4Y=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css" integrity="sha256-no0c5ccDODBwp+9hSmV5VvPpKwHCpbVzXHexIkupM6U=" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js" integrity="sha256-a5YRB27CcBwBFcT5EF/f3E4vzIqyHrSR878nseNYw64=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"hyw-zero.github.io","root":"/","images":"/images","scheme":"Gemini","version":"8.7.0","exturl":false,"sidebar":{"position":"left","display":"hide","padding":10,"offset":12,"scrollpercent":false,"onmobile":false},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta name="description" content="1.进程通信进程通信一般分为以下6类">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux进程通信(共享内存)">
<meta property="og:url" content="https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/index.html">
<meta property="og:site_name" content="ZERO">
<meta property="og:description" content="1.进程通信进程通信一般分为以下6类">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-05-01T15:26:46.000Z">
<meta property="article:modified_time" content="2021-08-22T09:07:10.109Z">
<meta property="article:author" content="hyw-zero">
<meta property="article:tag" content="进程通信">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/","path":"2019/05/01/linux进程通信-共享内存/","title":"Linux进程通信(共享内存)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Linux进程通信(共享内存) | ZERO</title>
  



<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="ZERO" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>
  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">ZERO</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">keep  learning, be  curious !</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1"><span class="nav-text">1.进程通信</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-text">2.共享内存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98api%E5%87%BD%E6%95%B0"><span class="nav-text">3.共享内存api函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-shmget%E5%87%BD%E6%95%B0%EF%BC%9A%E5%88%9B%E5%BB%BA%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-text">1.shmget函数：创建共享内存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-shmat%E5%87%BD%E6%95%B0%EF%BC%9A%E6%8C%82%E6%8E%A5%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-text">2.shmat函数：挂接共享内存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-shmdt%E5%87%BD%E6%95%B0%EF%BC%9A%E5%8E%BB%E5%85%B3%E8%81%94%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-text">3.shmdt函数：去关联共享内存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-shmctl%E5%87%BD%E6%95%B0%EF%BC%9A%E9%94%80%E6%AF%81%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-text">4.shmctl函数：销毁共享内存</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98%E4%BD%BF%E7%94%A8Demo"><span class="nav-text">4.共享内存使用Demo</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-serve-c"><span class="nav-text">1.serve.c</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-client-c"><span class="nav-text">2.client.c</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E9%99%84%E5%BD%95"><span class="nav-text">5.附录</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
            <div class="site-overview">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hyw-zero"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">hyw-zero</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">13</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="mailto:hyw33666@gmail.com" title="E-Mail → mailto:hyw33666@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://github.com/hyw-zero" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;hyw-zero" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      推荐阅读
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://c.biancheng.net/cplus/" title="http:&#x2F;&#x2F;c.biancheng.net&#x2F;cplus&#x2F;" rel="noopener" target="_blank">c语言中文网</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://github.com/chenshuo/documents/downloads" title="https:&#x2F;&#x2F;github.com&#x2F;chenshuo&#x2F;documents&#x2F;downloads" rel="noopener" target="_blank">Linux多线程服务端</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://github.com/SilverMaple/STLSourceCodeNote" title="https:&#x2F;&#x2F;github.com&#x2F;SilverMaple&#x2F;STLSourceCodeNote" rel="noopener" target="_blank">STL源码剖析</a>
        </li>
    </ul>
  </div>
<div class="cc-license animated" itemprop="sponsor">
  <a href="https://www.netlify.com" class="cc-opacity" title="Deploy with Netlify → https://www.netlify.com" target="_blank"><img width="80" src="https://www.netlify.com/img/global/badges/netlify-dark.svg" alt="Netlify"></a>
</div>
            </div>
        </div>
	    </div>
	  

    </div>
	<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=280 height=300 src="//music.163.com/outchain/player?type=0&id=411680085&auto=1&height=430"></iframe>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="hyw-zero">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ZERO">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Linux进程通信(共享内存)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-05-01 15:26:46" itemprop="dateCreated datePublished" datetime="2019-05-01T15:26:46Z">2019-05-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Linux/" itemprop="url" rel="index"><span itemprop="name">Linux</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="1-进程通信"><a href="#1-进程通信" class="headerlink" title="1.进程通信"></a>1.进程通信</h3><p>进程通信一般分为以下6类</p>
<span id="more"></span>

<ol>
<li><strong>共享内存（shared memory）：</strong>多个进程可以访问同一块内存空间。</li>
<li><strong>套接字（socket）：</strong>可用于不同计算机之间的进程间通信。</li>
<li><strong>信号量（semaphore）：</strong>用于进程之间对共享资源进行加锁。</li>
<li><strong>信号（signal）：</strong>信号用于通知其它进程有某种事件发生。</li>
<li><strong>消息队列（message）：</strong>进程可以向队列中添加消息，其它的进程则可以读取队列中的消息。</li>
<li><strong>管道（pipe）：</strong>包括无名管道，命名管道，无名管道可用于具有父进程和子进程之间的通信。命名管道克服了管道没有名字的限制，因此，除具有管道所具有的功能外，它还允许无亲缘关系进程间的通信。</li>
</ol>
<h3 id="2-共享内存"><a href="#2-共享内存" class="headerlink" title="2.共享内存"></a>2.共享内存</h3><p> <strong>共享内存（Shared Memory）：</strong>允许多个进程访问同一个内存空间，是在多个进程之间共享和传递数据最高效的方式。操作系统将不同进程之间共享内存安排为同一段物理内存，进程可以将共享内存连接到它们自己的地址空间中，如果某个进程修改了共享内存中的数据，其它的进程读到的数据也将会改变。</p>
<blockquote>
<p>弊端：共享内存没提供同步机制，通常需要与信号量搭配使用。</p>
</blockquote>
<h3 id="3-共享内存api函数"><a href="#3-共享内存api函数" class="headerlink" title="3.共享内存api函数"></a>3.共享内存api函数</h3><p>在Linux操作系统中，提供了一组函数用于操作共享内存。但是需要包含以下库函数</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/ipc.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br></pre></td></tr></table></figure>

<h4 id="1-shmget函数：创建共享内存"><a href="#1-shmget函数：创建共享内存" class="headerlink" title="1.shmget函数：创建共享内存"></a>1.shmget函数：创建共享内存</h4><p><strong>用于获取或者创建共享内存</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmget</span><span class="params">(<span class="keyword">key_t</span> key, <span class="keyword">size_t</span> size, <span class="keyword">int</span> shmflg)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 1. key_t key 参数key是共享内存的键值，是一个无符号整数，是共享内存在系统中的编号，不 *    同共享内存的编号不能相同，这一点由程序员保证。key最好使用16进制。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">* 2. size_t size 参数size是待创建的共享内存的大小，以字节为单位。</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">* 3. shmflg 是共享内存的访问权限，与文件的权限一样，0666|IPC_CREAT 表示全部用户对它可	读写，如果共享内存不存在，就创建一个共享内存。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h4 id="2-shmat函数：挂接共享内存"><a href="#2-shmat函数：挂接共享内存" class="headerlink" title="2.shmat函数：挂接共享内存"></a>2.shmat函数：挂接共享内存</h4><p><strong>用于把共享内存连接到当前进程的地址空间</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">shmat</span><span class="params">(<span class="keyword">int</span> shm_id, <span class="keyword">const</span> <span class="keyword">void</span> *shm_addr, <span class="keyword">int</span> shmflg)</span></span>;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 1. shm_id是由shmget函数返回的共享内存标识。</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">* 2. shm_addr指定共享内存连接到当前进程中的地址位置，通常为空，表示让系统来选择共享内存 *    的地址。</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">* 3. shm_flg是一组标志位，通常为0。调用成功时返回一个指向共享内存第一个字节的指针，如果 *    调用失败返回-1.</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h4 id="3-shmdt函数：去关联共享内存"><a href="#3-shmdt函数：去关联共享内存" class="headerlink" title="3.shmdt函数：去关联共享内存"></a>3.shmdt函数：去关联共享内存</h4><p><strong>用于将共享内存从当前进程中分离，相当于shmat函数的反操作。</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmdt</span><span class="params">(<span class="keyword">const</span> <span class="keyword">void</span> *shmaddr)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 1. shmaddr是shmat函数返回的地址。</span></span><br><span class="line"><span class="comment">* 调用成功时返回0，失败时返回-1.</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h4 id="4-shmctl函数：销毁共享内存"><a href="#4-shmctl函数：销毁共享内存" class="headerlink" title="4.shmctl函数：销毁共享内存"></a>4.shmctl函数：销毁共享内存</h4><p><strong>用于删除共享内存</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmctl</span><span class="params">(<span class="keyword">int</span> shm_id, <span class="keyword">int</span> command, struct shmid_ds *buf)</span></span>;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 1. shm_id是shmget函数返回的共享内存标识符。</span></span><br><span class="line"><span class="comment">* 2. command填IPC_RMID。。</span></span><br><span class="line"><span class="comment">* 3. buf填0。</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">*  shmctl是控制共享内存的函数，其功能不只是删除共享内容，但其它的功能没什么用。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="4-共享内存使用Demo"><a href="#4-共享内存使用Demo" class="headerlink" title="4.共享内存使用Demo"></a>4.共享内存使用Demo</h3><h4 id="1-serve-c"><a href="#1-serve-c" class="headerlink" title="1.serve.c"></a>1.serve.c</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* author:hyw</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/ipc.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SHM_SERIAL_NUM 0x2020</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SHM_SIZE       2048</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">free_shm_from_driver</span><span class="params">(<span class="keyword">void</span> * share_memory,<span class="keyword">int</span> shm_id)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="number">-1</span> == shmdt(share_memory))&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmdt(share_memory) fail! error= %d&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="number">-1</span> == shmctl(shm_id,IPC_RMID,<span class="number">0</span>))&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmdt(share_memory) fail! error= %d&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> shm_id = shmget((<span class="keyword">key_t</span>)SHM_SERIAL_NUM,SHM_SIZE,<span class="number">0660</span>|IPC_CREAT);</span><br><span class="line">    <span class="keyword">if</span>(shm_id == <span class="number">-1</span>)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Share memory create　fail! errno=%d&quot;</span>,errno);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">char</span>* p_str=shmat(shm_id,<span class="literal">NULL</span>,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span>((<span class="keyword">void</span> *)<span class="number">-1</span> == p_str)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmat(shm_id) fail! errno=%d&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span>(i&lt;<span class="number">25</span>)&#123;</span><br><span class="line">        <span class="built_in">snprintf</span>(p_str,<span class="number">500</span>,<span class="string">&quot;This is in serve process pid= %d,i=%d\n&quot;</span>,getpid(),++i);         <span class="comment">//write to share memory</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%s\n&quot;</span>,p_str);</span><br><span class="line">        sleep(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//free_shm_from_driver(p_str,shm_id);</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="2-client-c"><a href="#2-client-c" class="headerlink" title="2.client.c"></a>2.client.c</h4><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* author:hyw</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/ipc.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;errno.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SHM_SERIAL_NUM 0x2020</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SHM_SIZE       2048</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">free_shm_from_driver</span><span class="params">(<span class="keyword">void</span> * share_memory,<span class="keyword">int</span> shm_id)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="number">-1</span> == shmdt(share_memory))&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmdt(share_memory) fail! error= %d\n&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="number">-1</span> == shmctl(shm_id,IPC_RMID,<span class="number">0</span>))&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmdt(share_memory) fail! error= %d\n&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> shm_id = shmget((<span class="keyword">key_t</span>)SHM_SERIAL_NUM,SHM_SIZE,<span class="number">0660</span>|IPC_CREAT);</span><br><span class="line">    <span class="keyword">if</span>(shm_id == <span class="number">-1</span>)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Share memory create　fail! errno=%d&quot;</span>,errno);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">char</span>* p_str=shmat(shm_id,<span class="literal">NULL</span>,<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">if</span>((<span class="keyword">void</span> *)<span class="number">-1</span> == p_str)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;shmat(shm_id) fail! errno=%d&quot;</span>,errno);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span>(i&lt;<span class="number">100</span>)&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%s\n&quot;</span>,p_str); <span class="comment">//read from share memory</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%s%d\n&quot;</span>,<span class="string">&quot;This is in client process pid=&quot;</span>,getpid());</span><br><span class="line">        sleep(<span class="number">1</span>);</span><br><span class="line">        ++i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-附录"><a href="#5-附录" class="headerlink" title="5.附录"></a>5.附录</h3><p>linux 下查看共享内存命令 ipcs -m</p>

    </div>

    
    
    
	<div>
		
			<div>
	
		<div style="text-align:center;color: #ccc;font-size:16px;">---------------------------------------本文结束<i class="fa fa-paw"></i>感谢您的阅读---------------------------------------</div>
	
</div>
		
	</div>
	<div>
		
			
<div class="my_post_copyright">
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
<!-- JS库 sweetalert 可修改路径 -->
<script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<p><span>本文标题:</span><a href="/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/">Linux进程通信(共享内存)</a></p>
<!--
<p><span>文章作者:</span><a href="/" title="访问  的个人博客"></a></p>
-->
<p><span>发布时间:</span>2019年05月01日 - 15:26</p>
<p><span>最后更新:</span>2021年08月22日 - 09:07</p>
<p><span>原始链接:</span><a href="/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/" title="Linux进程通信(共享内存)">https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/</a>
<span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://hyw-zero.github.io/2019/05/01/linux%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98/" aria-label="复制成功！"></i></span>
</p>
<p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>
</div>
<script>
var clipboard = new Clipboard('.fa-clipboard');
$(".fa-clipboard").click(function(){
clipboard.on('success', function(){
swal({
title: "",
text: '复制成功',
icon: "success",
showConfirmButton: true
});
});
});
</script>

		
	</div>

    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wx.png" alt="hyw-zero 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.png" alt="hyw-zero 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="post-tags">
              <a href="/tags/%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1/" rel="tag"><i class="fa fa-tag"></i>进程通信</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2019/03/16/vim%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93/" rel="prev" title="vim常用快捷键">
                  <i class="fa fa-chevron-left"></i> vim常用快捷键
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2020/10/05/%E5%89%91%E6%8C%87offer%E7%AE%97%E6%B3%95%E7%BB%83%E4%B9%A0/" rel="next" title="剑指offer算法练习">
                  剑指offer算法练习 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="lv-container" data-id="city" data-uid="MTAyMC80MzU4NC8yMDEyMw=="></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2018 – 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hyw-zero</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
<div class="theme-info">
	<i class="fa fa-edit" style="font-size:18px"></i>
	<span class="post-count">博客全站共98.2k字</span>
</div>
    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/third-party/search/local-search.js"></script>



  <script class="next-config" data-name="nprogress" type="application/json">{"enable":true,"spinner":true}</script>
  <script src="/js/third-party/nprogress.js"></script>

  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script src="/js/third-party/comments/livere.js"></script>
</body>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/love.js"></script>
</html>

